package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        // 需求分析
        // 构建查询条件
        Wrapper<WmChannel> query = new QueryWrapper<>();
        // 判断用户是否输入了频道名称,有的话添加查询条件
        if (!StringUtils.isEmpty(dto.getName())) {
            ((QueryWrapper<WmChannel>) query).like("name", dto.getName());
        }
        // 构建分页条件
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        // 分页查询
        IPage<WmChannel> iPage = this.page(page, query);
        // 构建通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        return result;
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel entity) {
        // 判断输入的参数
        if (entity == null || StringUtils.isEmpty(entity.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据频道名称查询是否有历史记录
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName, entity.getName());
        int count = this.count(query);
        // 如果有,提示频道已经存在
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        // 没有,新增
        entity.setCreatedTime(new Date());
        this.save(entity);
        return ResponseResult.okResult(entity.getId());
    }
}
